#include "BtnLevel.h"
#include "MainGameScene.h"

using namespace cocos2d;



BtnLevel* BtnLevel::create(int level, int starNum)
{
    BtnLevel *pRet = new BtnLevel();
	pRet->d_level = level;
	pRet->d_starNum = starNum;
	pRet->d_isDisable = false;

	if(pRet->d_starNum > 3) {
		pRet->d_starNum = 3;
	}

    if (pRet && pRet->init()) {
        pRet->autorelease();

        return pRet;
    } else {
        delete pRet;
        pRet = NULL;
        return NULL;
    }
}

bool BtnLevel::init(){  
    if (!GameObj::init()) {  
        return false;  
    }

	this->setContentSize(CCSize(100, 100));

	CCLayerColor* bg = CCLayerColor::create(ccc4(0, 128, 255, 255), 100, 100);
	this->addChild(bg);
	
	char lv[5];
	sprintf(lv, "%d", d_level);
	CCLabelAtlas* pCostHp = CCLabelAtlas::create(lv, "number_02.png", 26, 35, '0');
	pCostHp->setPosition(ccp(50 - (pCostHp->getContentSize().width/2), 40));
	this->addChild(pCostHp);

	
	int currentLevel = d_setting->getMaxWave();
	if(currentLevel < d_level) {
		// disable
		CCLayerColor* disableFG = CCLayerColor::create(ccc4(192, 192, 192, 200), 100, 100);
		this->addChild(disableFG);
		d_isDisable = true;
	} else {
		for(int i = 0; i < d_starNum; i++) {
			CCSprite* star = CCSprite::create("bullet01.png");
			star->setScale(0.757);
			star->setPosition(ccp(20 + 30*i, 15));
			this->addChild(star);
		}
	}

    return true;  
} 

bool BtnLevel::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
	if(d_isDisable) {
		return false;
	}
	return true;
}

void BtnLevel::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
} 

void BtnLevel::ccTouchEnded(CCTouch* touch, CCEvent* event)  
{  
    CCPoint sLocalPos = convertToNodeSpace(touch->getLocation());  
    CCRect sRC = CCRect(getPositionX() - getContentSize().width * getAnchorPoint().x,  
                           getPositionY() - getContentSize().height * getAnchorPoint().y,  
                           getContentSize().width, getContentSize().height);  
      
      
    sRC.origin = CCPointZero;  
    bool isTouched = sRC.containsPoint(sLocalPos);  
    if(isTouched)  
    {  
		d_setting->setWave(d_level);
		CCDirector::sharedDirector()->replaceScene(MainGameScene::scene());
    }
} 

void BtnLevel::onEnter()  
{  
    CCDirector* pDirector = CCDirector::sharedDirector();  
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, false);  
    CCSprite::onEnter();  
}  
  
void BtnLevel::onExit()  
{  
    CCDirector* pDirector = CCDirector::sharedDirector();  
    pDirector->getTouchDispatcher()->removeDelegate(this);  
    CCSprite::onExit();  
} 